// 话题
const Topics = require('../models/Topics')
// 用户
const Users = require('../models/Users')
// 问题
const Questions = require('../models/Questions')

class TopicsCtl {
    async find(ctx) {
        // Math.max在接受的参数中选择最大的一个
        // 每页条数
        const perPage = Math.max(ctx.query.perPage * 1, 10) || 10
        // 当前页
        const page = Math.max(ctx.query.page * 1, 1) || 1
        // 跳过的条数
        const skip = (page - 1) * perPage
        // 分页 模糊搜索
        const q = new RegExp(ctx.query.q)
        const list = await Topics.find({name: q}).limit(perPage).skip(skip).select("+introduction").sort({createdAt: -1})
        // 总页数
        const total = await Topics.find({name: q}).countDocuments()
        // 向上取整 一共有多少页
        const totalPage = Math.ceil(total / perPage)
        ctx.body = {
            page,
            perPage,
            list,
            total,
            totalPage
        }
    }

    async findById(ctx) {
        // 是否显示 fields
        // http://localhost:3000/topics/5e48e26bfb874d2f6ca2ace7?fields=introduction
        // ?fields后面写上指定的参数，即可返回指定的字段
        const {fields = ''} = ctx.query
        const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
        const topic = await Topics.findById(ctx.params.id).select(selectFields)
        if (!topic) ctx.throw(404, '此话题不存在')
        ctx.body = topic
    }
    //TODO 创建话题已存在，还可以重复创建，等待解决
    async create(ctx) {
        // 验证 话题名是必须的，所以required为true；其他不是必须的，使用required为false
        ctx.verifyParams({
            name: {type: 'string', required: true},
            avatar_url: {type: 'string', required: false},
            introduction: {type: 'string', required: false}
        })
        ctx.request.body.user = ctx.state.user._id
        const topic = await new Topics(ctx.request.body).save()
        ctx.body = topic
    }

    // 授权处理中间件
    async checkOwner(ctx, next) {
        ctx.body = ctx.state
        if(!ctx.state.userId) {// TODO 之前没有设计话题的创建者，现在走个后门
            await next()
        }
        if (ctx.state.userId.toString() !== ctx.state.user._id) {
            ctx.throw(403, '没有权限')
        } else { 
            await next()
        }
    }

    async update(ctx) {
        ctx.verifyParams({
            name: {type: 'string', required: false},
            avatar_url: {type: 'string', required: false},
            introduction: {type: 'string', required: false}
        })
        const topic = await Topics.findByIdAndUpdate(ctx.params.id, ctx.request.body)
        ctx.body = topic
        // 注：返回的是更新前的topic，mongoose的findByIdAndUpdate语法问题，待优化
    }

    async remove(ctx) {
        var topic = await Topics.findByIdAndRemove(ctx.params.id)
        if (!topic) ctx.throw(404, '此话题不存在')
        ctx.body = {message: '删除成功'}
    }


    // 校验话题是否存在
    async checkTopicExist(ctx, next) {
        const topic = await Topics.findById(ctx.params.id)
        if (!topic) {
            ctx.throw(404, '话题不存在')
        } else {
            ctx.state.userId = topic.user
            await next()
        }
    }

    // 关注话题
    async followTopic(ctx) {
        // 已经登录就有ctx.state.user字段
        const me = await Users.findById(ctx.state.user._id).select('+followingTopics')
        // {
        //     avatar_url: null,
        //     gender: 'male',
        //     headline: null,
        //     followingTopics: [ 61bc04bb92b33d678ca2368d, 61bc04df92b33d678ca23690 ],
        //     _id: 61bff83a50ef6c51ec1392ba,
        //     name: '任盈盈',
        //     password: '123456',
        //     createdAt: 2021-12-20T03:27:54.843Z,
        //     updatedAt: 2021-12-20T08:35:56.992Z
        // }
        if (!me.followingTopics.map(id => id.toString()).includes(ctx.params.id)) {
            me.followingTopics.unshift(ctx.params.id)
            me.save()
            ctx.status = 204//关注话题成功
        } else {
            ctx.body = {message: "您已关注此话题"}
        }
    }

    // 取消关注话题
    async unfollowTopic(ctx) {
        // 已经登录就有ctx.state.user字段
        var me = await Users.findById(ctx.state.user._id).select('+followingTopics')
        // 获取要取消关注的人的id在自己列表中following数组的下标
        var index = me.followingTopics.map(id => id.toString()).indexOf(ctx.params.id)
        if (index > -1) {
            me.followingTopics.splice(index, 1)
            me.save()
            ctx.status = 204//取消关注话题成功
        } else {
            ctx.body = {message: "您已取消关注此话题"}
        }
    }

    // 获取话题的粉丝列表 followingTopics包含话题的id
    async listFollowers(ctx) {
        // const users=await Users.find().select('+followingTopics')
        // {
        //     "avatar_url": null,
        //     "gender": "male",
        //     "headline": null,
        //      "followingTopics": [
        //         "61bc04bb92b33d678ca2368d"
        //     ],
        //     "_id": "61baecf6fed1b55bec39a146",
        //     "name": "独孤求败",
        //     "password": "123456",
        //     "createdAt": "2021-12-16T07:38:30.736Z",
        //     "updatedAt": "2021-12-20T09:32:41.576Z"
        // },
        // {
        //     "avatar_url": null,
        //     "gender": "male",
        //     "headline": null,
        //     "followingTopics": [],
        //     "_id": "61baf4acb8ee320d68f3abe7",
        //     "name": "令狐冲",
        //     "password": "123456",
        //     "createdAt": "2021-12-16T08:11:24.018Z",
        //     "updatedAt": "2021-12-20T10:13:05.587Z"
        // },
        // {
        //     "avatar_url": null,
        //     "gender": "male",
        //     "headline": null,
        //     "followingTopics": [
        //         "61bc04bb92b33d678ca2368d",
        //         "61bc04df92b33d678ca23690"
        //     ],
        //     "_id": "61bff83a50ef6c51ec1392ba",
        //     "name": "任盈盈",
        //     "password": "123456",
        //     "createdAt": "2021-12-20T03:27:54.843Z",
        //     "updatedAt": "2021-12-21T07:11:28.351Z"
        // },
        // ...
        const users = await Users.find({followingTopics: ctx.params.id})
        ctx.body = users
    }

    // 获取用户的关注话题列表 用户-话题多对多关系
    async listFollowingTopics(ctx) {
        // const user=await Users.findById(ctx.params.id).select('+followingTopics')
        // {
        //     "avatar_url": null,
        //     "gender": "male",
        //     "headline": null,
        //     "followingTopics": [
        //         "61bc04bb92b33d678ca2368d",
        //         "61bc04df92b33d678ca23690"
        //     ],
        //     "_id": "61bff83a50ef6c51ec1392ba",
        //     "name": "任盈盈",
        //     "password": "123456",
        //     "createdAt": "2021-12-20T03:27:54.843Z",
        //     "updatedAt": "2021-12-21T07:11:28.351Z"
        // }
        // 显示followingTopics字段，followingTopics字段里面只有id；根据id查询用户具体信息和话题列表，需要集合联合查询
        const user = await Users.findById(ctx.params.id).populate('followingTopics')
        if (!user) {
            ctx.throw(404)
        }
        ctx.body = user
    }

    // 获取话题的问题列表
    // 提问者-问题 一对多关系
    async listQuestions(ctx) {
        const questions = await Questions.find({topics: ctx.params.id})
        ctx.body = questions
    }
}

module.exports = new TopicsCtl()
